#!/bin/bash
set -e

handle_error() {
    echo "错误发生在 $1 行，命令为 $2"
    # 如果有异常，恢复track_activities参数
    $OSEXEC gs_guc reload -N all -I all -c "track_activities = on" >> $mig_log_filename 2>&1
    exit 1
}

trap 'handle_error $LINENO "$BASH_COMMAND"' ERR

## 打印分阶段迁移汇总日志
function print_mig_log {
   echo "" 
   echo "-----------------------"
   awk 'BEGIN { found=0 } /ObjectName Type Summary/ { found=NR } END { if (found > 0) { for (i=found; i<=NR; i++) print lines[i] } } { lines[NR]=$0 }' $mig_log_filename
}

## 分步迁移
function step_mig {
echo $(date +%F%n%T) $2 开始
if [ "$1" == "mig-tab-data" ]; then
    mtk_config_file=mtk-onlydata.json
else
    mtk_config_file=mtk-metadata.json
fi
$HOMEDIR/workspace/mtk/mtk -c $HOMEDIR/workspace/mtk/$mtk_config_file $1 -r ./report/$1 >> $mig_log_filename 2>&1
print_mig_log
echo $(date +%F%n%T) $2 完成
}

## 检查连接
function chech_connection {
    echo $(date +%F%n%T) 检查数据库连接 开始
    echo 检查源库连接
    $HOMEDIR/workspace/mtk/mtk -c $HOMEDIR/config/mtk-config.json usql --source -C "SELECT * from product_component_version;"
    echo 检查目标库连接
    $HOMEDIR/workspace/mtk/mtk -c $HOMEDIR/config/mtk-config.json usql --target -C "select version();"
    echo $(date +%F%n%T) 检查数据库连接 完成
}

## 初始化迁移运行环境
function init_mig_runtime {
echo $(date +%F%n%T) 初始化迁移软件环境 开始
export HOMEDIR=$(dirname $(readlink -f "${BASH_SOURCE[0]}"))
source $HOMEDIR/scripts/init-env.sh
yum localinstall $HOMEDIR/dependencies/*`arch`.rpm $HOMEDIR/dependencies/*noarch.rpm -y
unzip -q -o -j $HOMEDIR/$pkg_oracle_client -d $HOMEDIR/workspace/oracle-client

#export LD_LIBRARY_PATH=$HOMEDIR/workspace/oracle-client:$LD_LIBRARY_PATH
tar -xf $HOMEDIR/$pkg_mtk --strip-components=1 -C $HOMEDIR/workspace/mtk
tar -xf $HOMEDIR/$pkg_mvd --strip-components=1 -C $HOMEDIR/workspace/mtk
cp -rf $HOMEDIR/config/license.json $HOMEDIR/workspace/mtk/
cd $HOMEDIR/workspace/mtk

if [ "$arch_result" == "aarch64" ]; then
    cp -rf mvd_linux_aarch64 mvd_linux_arm64
fi

if $($HOMEDIR/workspace/mtk/mtk --version | grep -q "MMMMMMMM"); then
    echo "MTK license验证通过"
else
    echo "MTK license验证失败"
    exit 1
fi

echo $(date +%F%n%T) 初始化迁移软件环境 完成
}

## 转换完整迁移配置文件
function convert_config_file {
target_db_encoding=`$HOMEDIR/workspace/mtk/mtk -c $HOMEDIR/config/mtk-config.json usql --target -C "select pg_encoding_to_char(encoding) a from pg_catalog.pg_database where datname= current_database();" --csv | tail -n 1`

if [ "$target_db_encoding" == "GBK" ]; then
source_client_encoding="ZHS16GBK"
target_client_encoding="GBK"
elif [ "$target_db_encoding" == "GB18030" ]; then
source_client_encoding="ZHS32GB18030"
target_client_encoding="GB18030"
else
source_client_encoding="AL32UTF8"
target_client_encoding="UTF8"
fi

jq --argfile input $HOMEDIR/config/mtk-config.json \
   '.source.connect = $input.source.connect | 
    .target.connect = $input.target.connect | 
    .source.connect.clientCharset = "AL32UTF8" | 
    .target.connect.clientCharset = "UTF8" | 
    .object.schemas = $input.object.schemas' \
   $HOMEDIR/config/template/mtk-template.json \
   > $HOMEDIR/workspace/mtk/mtk-metadata.json

jq --argfile input $HOMEDIR/config/mtk-config.json \
   --arg source_client_encoding "$source_client_encoding" \
   --arg target_client_encoding "$target_client_encoding" \
   '.source.connect = $input.source.connect | 
    .target.connect = $input.target.connect | 
    .source.connect.clientCharset = $source_client_encoding | 
    .target.connect.clientCharset = $target_client_encoding | 
    .object.schemas = $input.object.schemas' \
   $HOMEDIR/config/template/mtk-template.json \
   > $HOMEDIR/workspace/mtk/mtk-onlydata.json
}

## 程序开始位置
# 初始化迁移软件运行环境
init_mig_runtime
# 检查连接
chech_connection
# 转换完整配置文件
convert_config_file
# 生成日志id
unique_id=$(date +%s%N)
mig_log_filename=$HOMEDIR/log/mig-log-$unique_id.log

echo "----------------"
echo "本会话仅输出概要日志，详细日志见:  tail -f $mig_log_filename"
echo "----------------"
echo ""

# 临时关闭track_activities，提高迁移速度
$OSEXEC gs_guc reload -N all -I all -c "track_activities = off" >> $mig_log_filename 2>&1

if [ "$1" == "onlydata" ] ; then

step_mig mig-tab-data 迁移表数据
step_mig sync-alter-sequence 同步序列
step_mig sync-coll-statistics 收集统计信息

else

echo  $(date +%F%n%T) 创建用户 开始
source $HOMEDIR/scripts/create-user.sh >> $mig_log_filename 2>&1
grep "create user" "$mig_log_filename"
echo  $(date +%F%n%T) 创建用户 完成

step_mig mig-tab-pre 迁移表和类型（第一次）
step_mig sync-synonym 迁移同义词
step_mig sync-object-type 迁移类型（第二次）
step_mig sync-object-type 迁移类型（第三次）
step_mig sync-function 迁移函数
step_mig sync-procedure 迁移过程
step_mig sync-view 迁移视图
step_mig sync-mview 迁移物化视图
step_mig mig-tab-data 迁移表数据
step_mig mig-tab-post 迁移索引、约束、序列
step_mig sync-package 迁移包

echo $(date +%F%n%T) 编译无效对象 开始
source $HOMEDIR/scripts/recompile.sh
source $HOMEDIR/scripts/recompile.sh
echo $(date +%F%n%T) 编译无效对象 完成

step_mig sync-view 迁移视图（第二次）
step_mig sync-mview 移物化视图（第二次）
step_mig sync-coll-statistics 收集统计信息
step_mig sync-trigger 迁移触发器

# 恢复track_activities
$OSEXEC gs_guc reload -N all -I all -c "track_activities = on" >> $mig_log_filename 2>&1

echo $(date +%F%n%T) 迁移权限 开始
source $HOMEDIR/scripts/mig-privilege.sh >> $mig_log_filename 2>&1
echo $(date +%F%n%T) 迁移权限 完成

echo "--------------------------------------------"
echo 检查元数据一致性
source $HOMEDIR/scripts/check-metadata.sh

fi

echo "--------------------------------------------"
echo 检查数据一致性
source $HOMEDIR/scripts/check-data.sh 


